<?php
namespace app\api\controller;
use app\common\BaseController;
use app\api\model\User as UserModel;
use app\common\Logs;
class User extends BaseController{    

    public function __construct(UserModel $userModel){
        parent::__construct();
        $this->model = $userModel;
    }
    
    public function login(){
        $params = $this->request->param();
        if(empty($params['userName']) || empty($params['password'])){
            return array('status'=>0,'msg'=>'用户名或密码不能为空！');
        }             
        $user = $this->model->where(['user_name'=>$params['userName'],'password'=>md5(md5($params['password']))])->find();
        if($user){
            if($user['lock']){
                return array('status'=>0,'msg'=>'该用户已被锁定，请联系管理员！');
            }
            $token = base64_encode(md5($params['userName'].time()));       
            $this->model->allowField(true)->isUpdate(true)->save(['token'=>$token,'login_time'=>time()],['user_name'=>$params['userName'],'password'=>md5(md5($params['password']))]);            
            return array('status'=>1,'token' => $token);
        }else{
            return array('status'=>0,'msg'=>'用户名或密码错误！');
        }        
    }

    public function checkPassword(){
        $params = $this->request->param();   
        if(empty($params['userId']) || empty($params['password'])){
            return array('status'=>0,'msg'=>'用户名ID或密码不能为空！');
        }             
        $user = $this->model->where(['id'=>$params['userId'],'password'=>md5(md5($params['password']))])->find();
        if($user){             
            return array('status'=>1,'msg' => '密码正确');
        }else{
            return array('status'=>0,'msg'=>'密码错误！');
        }        
    }

    public function changePassword(){
        $params = $this->request->param();   
        if(empty($params['userId']) || empty($params['password'])){
            return array('status'=>0,'msg'=>'新密码不能为空！');
        }       
      
        $user = $this->model->allowField(true)->isUpdate(true)->save(['password'=>md5(md5($params['password']))],['id'=>$params['userId']]);      
        if($user){                         
            return array('status'=>1,'msg' => '修改密码成功');
        }else{
            return array('status'=>0,'msg'=>'修改密码失败');
        }  
         
    }

    public function get_info(){
        $params = $this->request->param();
        if(empty($params['token'])){
            return 'token不能为空!';
        }             
        $user = $this->model->with('access')->where('token',$params['token'])->find();
        if(!$user){           
            return 'token错误！';
        } 
        return $user;   
    }

    public function logout(){
        $params = $this->request->param();      
        if(empty($params['token'])){
            return 'token不能为空!';
        }      
        $this->model->allowField(true)->isUpdate(true)->save(['token'=>''],['token'=>$params['token']]);
        return $token; 
    }
}
